<template>
  <div class="container">
    <div class="nav-bar">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>前端管理</el-breadcrumb-item>
        <el-breadcrumb-item>文章列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container-main">
      <Search
        :searchList='searchList'
        size="mini"
        class="mb-10"
        @search="searchHandle('search', $event)"
        @refresh="searchHandle('refresh', $event)"
      />
      <div class="main-handle">
        <div class="handle-item" v-if="handleType != 'add' && handleType != 'unPass'">
          <div class="item-title">文章选择</div>
          <el-select v-model="currentHandleId" placeholder="请选择文章内容" size="mini" @change="selectContent">
            <el-option v-for="item in atrList" :key="item.id" :label="item.fileUrl" :value="item.id" />
          </el-select>
        </div>
        <div class="handle-item" v-if="handleType != 'add' && handleType != 'unPass'">
          <el-button type="primary" size="mini" @click="commonHandle({ type: 'add' })">添加文章</el-button>
          <el-button type="primary" size="mini" @click="commonHandle({ type: 'edit' })">修改文章保存</el-button>
          <el-button type="primary" size="mini" @click="commonHandle({ type: 'delete' })">删除当前文章</el-button>
        </div>
        <div class="handle-item" v-if="handleType == 'add' || handleType == 'unPass'">
          <el-button type="primary" size="mini" @click="commonHandle({ type: 'load' })">取消添加文章</el-button>
          <el-button type="primary" size="mini" @click="commonHandle({ type: 'saveAdd' })">保存新文章</el-button>
        </div>
      </div>

      <div class="main-content">
        <el-form ref="submitForm" :model="formData" label-width="80px" label-position="left" :rules="rules">
          <el-form-item label="文章题目" prop="fileUrl">
            <el-input v-model="formData.fileUrl" size="mini" :disabled="handleType == 'see'" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <ueditor v-model="formData.content" />
          </el-form-item>
          <el-form-item label="相关文件" prop="fileurl">
            <UploadFile :filesList="formData.fileurl" @change="getFile" @delete="deleteFile" :formType="handleType"/>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import ueditor from '../../components/Common/ueditor'
import Search from '../../components/Common/Search'
import UploadFile from '../../components/Common/UploadFile'

export default {
  data() {
    return {
      searchList: [
        { value: '', key: 'fileUrl', type: 'input', placeholder: '请输入文章名称' }
      ],
      currentHandleId: '',
      article: '',
      atrList: [],
      handleType: '',
      formData: {},
      rules: {
        // fileUrl: [
        //     { required: true, message: '请输入标题', trigger: 'change' },
        // ],
        // content: [
        //     { required: true, message: '请输入文章内容', trigger: 'change' },
        // ],
      }
    }
  },
  created() {
    this._getPage()
  },
  components: {
    ueditor,
    Search,
    UploadFile
  },
  methods: {
    selectContent(val) {
      this.currentHandleId = val
      this._loadById()
    },
    getFile (file) {
      this.formData.fileurl.push(file)
    },
    deleteFile({ item, index }) {
      this.formData.fileurl.splice(index, 1)
    },
    searchHandle(type, form) {
      this.searchForm = form
      this.currentHandleId = ''
      if (type === 'search') {
        this._getPage(form)
      } else if (type === 'refresh') {
        this._getPage()
        this.searchList.forEach(item => {
          item.value = ''
        })
      }
    },
    commonHandle({ type, item }) {
      this.$refs['submitForm'].validate((valid) => {
        if (!valid) return
      })

      this.handleType = type
      if (type === 'edit' || type === 'saveAdd') {
        this.submitHandle()
      } else if (type === 'delete') {
        this._deleteById()
      } else if (type === 'add') {
        this.formData = {
          fileurl: []
        }
      } else if (type === 'load') {
        this._loadById()
      }
    },
    // 删除单个文章
    _deleteById() {
      this.$confirm(`您真的要删除此文章吗`, `温馨提示`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.$api.usDelete(this.currentHandleId)
          .then(res => {
            if (res.code === 200) {
              this.currentHandleId = ''
              this.$message.success('删除成功')
              this._getPage()
            } else {
              this.$message.warning(res.text || '服务器出现错误')
            }
          })
      })
    },
    // 新增/修改需求提交
    submitHandle() {
      this.$refs['submitForm'].validate((valid) => {
        if (valid) {
          let API = 'usUpdate'
          if (this.handleType === 'saveAdd') {
            API = 'usCreate'
          }

          this.$api[API](this.formData, this.currentHandleId).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.currentHandleId = res.data?.id
              this._getPage()
            } else {
              this.$message({
                message: res.text,
                type: 'warning'
              })
            }
          })
        } else {
          this.handleType = 'unPass'
        }
      })
    },
    // 获取列表
    async _getPage(form = {}) {
      this.tableLoading = true
      const res = await this.$api.usPage({
        page: this.currentPage,
        size: 10000,
        ...form
      })

      this.tableLoading = false
      if (res.code === 200) {
        this.atrList = res.data.rows
        this.currentHandleId = this.currentHandleId ? this.currentHandleId : this.atrList[0]?.id
        this._loadById()
      }
    },
    // 获取某个文章信息
    async _loadById() {
      const res = await this.$api.usLoad(this.currentHandleId)
      if (res.code === 200) {
        this.formData = res.data
        this.formData.fileurl = []
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.container-main{
  padding-bottom: 40px;
}
.main-handle{
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .handle-item{
    display: flex;
    align-items: center;
    margin-right: 20px;
    .item-title{
      margin-right: 20px;
      font-size: 14px;
    }
  }
}
</style>

